﻿using System;
using FireStarter.Base;
using FireStarter.Base.BusinessObjectMerger;
using Firestarter.DB.Schema.BO;

namespace Firestarter.DB.Schema.Logic
{
    public class DBMergeDBKeyColumn : DBMergeBO<DBKeyColumn>
    {
        protected override void CopyRelationships(DBKeyColumn fromKeyColumn, DBKeyColumn toKeyColumn)
        {
            //We only have to deal with the case of merging a DBPrimaryKeys Column relationship.
            // The merging of this relationship is not standard since we need to find the 
            // column from the toTable and and linke this PrimaryKeyColumn to it.
            if (fromKeyColumn == null) return;
            if (fromKeyColumn.Column == null) return;
            var foundColumn = FindToColumn(fromKeyColumn, toKeyColumn);
            toKeyColumn.Column = foundColumn ?? CreateColumn(toKeyColumn.Key, fromKeyColumn);
        }

        private DBColumn CreateColumn(DBKey toKey, DBKeyColumn fromKeyColumn)
        {
            if (toKey == null || toKey.Table == null) return null;
            var columnMerger = MergeableBORegistry.Instance.Resolve<DBColumn>();
            var column = columnMerger.MergeBOFrom(fromKeyColumn.Column, null);
            toKey.Table.Columns.Add(column);
            return column;
        }

        private static DBColumn FindToColumn(DBKeyColumn fromBO, DBKeyColumn toBO)
        {
            return toBO.Key.Table.Columns.Find(column => column.ColumnName == fromBO.ColumnName);
        }

        public override Func<DBKeyColumn, bool> MatchBusinessObject(DBKeyColumn boToFind)
        {
            return foundBO => boToFind != null && foundBO != null && foundBO.ColumnName == boToFind.ColumnName;
        }
    }
}